package com.zjgxzh.agentservice.controller;

import com.zjgxzh.agentservice.pojo.Agent;
import com.zjgxzh.agentservice.pojo.AgentTemplate;
import com.zjgxzh.agentservice.pojo.CreatePost;
import com.zjgxzh.agentservice.pojo.ResponseDialog;
import com.zjgxzh.agentservice.service.AgentService;
import com.zjgxzh.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;


@CrossOrigin
@RestController
@RequestMapping("/thread")
public class ThreadController {
    @Autowired
    AgentService agentService;

    @PostMapping("/create")
    public Result<Agent> createAgent(@RequestBody CreatePost post){
        //根据智能体模版创建对话
        //事先要设计好3个模版，并且事先向RAGFLow发请求，并存储assistant_id
        //post.getTemplate()就是选择的模版的名称

        System.out.println(post.getTemplate());
        String assistantId = AgentTemplate.assistantIds.get(post.getTemplate());
        AgentTemplate agentTemplate = AgentTemplate.templates.get(post.getTemplate());
        //根据模版用assistant_id向RAGFlow发送请求，创建后thread_id就是结果
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<Map<String, Object>> request = mapOf((map)->{
            map.put("inputs", null);
            map.put("query", "现在开始模拟面试，请你先自我介绍，等我回复后再开始提问");
            map.put("response_mode", "blocking");
            map.put("user", "zjgxzh");
            map.put("files", null);
            map.put("conversation_id", "");
        }, assistantId);
        ResponseDialog resDialog = restTemplate.postForObject("https://api.dify.ai/v1/chat-messages", request, ResponseDialog.class );
        System.out.println(resDialog);
        Agent resAgent = new Agent(resDialog.getConversation_id(),assistantId, post.getUsername(),
                agentTemplate.getName(), agentTemplate.getDescription(),agentTemplate.getIcon());
        System.out.println(resAgent);
        //然后在Agent表里创建一项，记录下来
        agentService.addAgent(resAgent);
        return Result.success(resAgent);
    }

    public static HttpEntity<Map<String, Object>> mapOf(Consumer<Map<String,Object>> adder, String key){
        Map<String, Object> requestBody = new HashMap<>();
        adder.accept(requestBody);
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        requestHeaders.setBearerAuth(key);
        HttpEntity<Map<String, Object>> r = new HttpEntity<Map<String, Object>>(requestBody, requestHeaders);
        return r;
    }

}


